package dfs;

/**
 * @author wcj
 * @Date 2021/7/6 20:11
 * @Version 1.0
 */
public class IsLand {

    private static int count;
    private static int row;
    private static int col;
    private static int[][] tmp;

    /**
     * 岛屿问题
     * 深搜：
     * ①递归方法设计：dfs(int i,int j)其中i,j代表二维数组的坐标
     * ②递归出口：i,j越界，截止
     * ③递归组合方式：上下左右四个方向进行深搜
     * 思想：采用染色的思想，对二维数组进行遍历，如果为1，进行深搜，将能够搜索到的1全部标记为2
     *
     * @param isLand
     * @return
     */
    public static int isLand(int[][] isLand) {
        count = 0;
        tmp = isLand;
        row = isLand.length;
        col = isLand[0].length;
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < col; j++) {
                if (isLand[i][j] == 1) {
                    dfs(i, j);
                    count++;
                }
            }
        }
        return count;
    }

    public static void dfs(int i, int j) {
        if (i < 0 || i >= row || j < 0 || j >= col) {
            return;
        }
        if (tmp[i][j] == 1) {
            tmp[i][j] = 2;
            dfs(i - 1, j);
            dfs(i + 1, j);
            dfs(i, j - 1);
            dfs(i, j + 1);
        }
    }
}
